#!/bin/bash

set -o errexit

download(){
  # wget安装
  if [[ ! `which wget` ]]; then
    if check_sys sysRelease ubuntu;then
        apt-get install -y wget
    elif check_sys sysRelease centos;then
        yum install -y wget
    fi 
  fi

  local url1=$1
  local url2=$2
  local filename=$3
  
  speed1=`curl -m 5 -L -s -w '%{speed_download}' "$url1" -o /dev/null || true`
  speed1=${speed1%%.*}
  speed2=`curl -m 5 -L -s -w '%{speed_download}' "$url2" -o /dev/null || true`
  speed2=${speed2%%.*}
  echo "speed1:"$speed1
  echo "speed2:"$speed2
  url=$url1
  if [[ $speed2 -gt $speed1 ]]; then
    url=$url2
  fi
  echo "using url:"$url
  wget "$url" -O $filename

}

#判断系统版本
check_sys(){
    local checkType=$1
    local value=$2

    local release=''
    local systemPackage=''
    local packageSupport=''

    if [[ "$release" == "" ]] || [[ "$systemPackage" == "" ]] || [[ "$packageSupport" == "" ]];then

        if [[ -f /etc/redhat-release ]];then
            release="centos"
            systemPackage="yum"
            packageSupport=true

        elif cat /etc/issue | grep -q -E -i "debian";then
            release="debian"
            systemPackage="apt"
            packageSupport=true

        elif cat /etc/issue | grep -q -E -i "ubuntu";then
            release="ubuntu"
            systemPackage="apt"
            packageSupport=true

        elif cat /etc/issue | grep -q -E -i "centos|red hat|redhat";then
            release="centos"
            systemPackage="yum"
            packageSupport=true

        elif cat /proc/version | grep -q -E -i "debian";then
            release="debian"
            systemPackage="apt"
            packageSupport=true

        elif cat /proc/version | grep -q -E -i "ubuntu";then
            release="ubuntu"
            systemPackage="apt"
            packageSupport=true

        elif cat /proc/version | grep -q -E -i "centos|red hat|redhat";then
            release="centos"
            systemPackage="yum"
            packageSupport=true

        else
            release="other"
            systemPackage="other"
            packageSupport=false
        fi
    fi

    echo -e "release=$release\nsystemPackage=$systemPackage\npackageSupport=$packageSupport\n" > /tmp/ezhttp_sys_check_result

    if [[ $checkType == "sysRelease" ]]; then
        if [ "$value" == "$release" ];then
            return 0
        else
            return 1
        fi

    elif [[ $checkType == "packageManager" ]]; then
        if [ "$value" == "$systemPackage" ];then
            return 0
        else
            return 1
        fi

    elif [[ $checkType == "packageSupport" ]]; then
        if $packageSupport;then
            return 0
        else
            return 1
        fi
    fi
}

get_sys_ver() {
cat > /tmp/sys_ver.py <<EOF
import platform
import re

sys_ver = platform.platform()
sys_ver = re.sub(r'.*-with-(.*)-.*',"\g<1>",sys_ver)
if sys_ver.startswith("centos-7"):
    sys_ver = "centos-7"
if sys_ver.startswith("centos-6"):
    sys_ver = "centos-6"
print sys_ver
EOF
echo `python /tmp/sys_ver.py`
}

upgrade_db() {
eval `grep MYSQL_PASS /opt/cdnfly/master/conf/config.py`
eval `grep MYSQL_IP /opt/cdnfly/master/conf/config.py`
eval `grep MYSQL_PORT /opt/cdnfly/master/conf/config.py`
eval `grep MYSQL_DB /opt/cdnfly/master/conf/config.py`
eval `grep MYSQL_USER /opt/cdnfly/master/conf/config.py`


mysql -N -h$MYSQL_IP -u$MYSQL_USER -p$MYSQL_PASS -P$MYSQL_PORT $MYSQL_DB -e 'show processlist' | awk '{print $1}' | xargs kill || true
supervisorctl stop cc_auto_switch site_res_count site_sync task node_monitor
cat > /tmp/_db.py <<'EOF'
# -*- coding: utf-8 -*-

import sys
sys.path.append("/opt/cdnfly/master/")
from model.db import Db
import pymysql
import json
reload(sys) 
sys.setdefaultencoding('utf8')

conn = Db()
try:
    # 清空line表task_id
    conn.execute("update line set task_id=null;")
    conn.commit()

    # 建表
    if not conn.fetchone("SHOW TABLES LIKE 'cname_domain'"):
        conn.execute("CREATE TABLE `cname_domain` (`id` int(11) NOT NULL AUTO_INCREMENT,`des` varchar(255) DEFAULT NULL,`domain` varchar(255) DEFAULT NULL,PRIMARY KEY (`id`)) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;")
        conn.commit()

    # tlock
    if not conn.fetchone("select * from tlock where name='cname_domain'"):
        conn.execute("insert into `tlock` values ('cname_domain')")

    # 查出所有cname域名
    cname_domains = {}

    main_domain = json.loads(conn.fetchone("select value from config where name='dns_config'")['value'])["domain"]
    cname_domains[main_domain] = ""

    sites = conn.fetchall("select distinct cname_domain from site where INSTR(`cname_domain`, '.') > 0 ")
    for site in sites:
        cname_domains[site['cname_domain']] = ""

    streams = conn.fetchall("select distinct cname_domain from stream where INSTR(`cname_domain`, '.') > 0")
    for stream in streams:
        cname_domains[stream['cname_domain']] = ""

    user_packages = conn.fetchall("select distinct cname_domain from user_package where INSTR(`cname_domain`, '.') > 0")
    for user_package in user_packages:
        cname_domains[user_package['cname_domain']] = ""

    packages = conn.fetchall("select distinct cname_domain from package where cname_domain is not null and cname_domain != '' and INSTR(`cname_domain`, '.') > 0 ")
    for package in packages:
        cname_domains[package['cname_domain']] = ""

    # 插入cname_domain表
    for domain in cname_domains:
        domain_row = conn.fetchone("select id from cname_domain where domain=%s", domain)
        if domain_row:
            cname_domains[domain] = domain_row["id"]
        else:
            conn.execute("insert into cname_domain values (null, '',%s)", domain)
            insert_id = conn.insert_id()
            conn.commit()
            cname_domains[domain] = insert_id

    # 更新package
    conn.execute("update package set cname_domain=%s where cname_domain is null or cname_domain = '' ", cname_domains[main_domain] )
    conn.commit()

    # 更新package site user_package stream
    for domain in cname_domains:
        conn.execute("update package set cname_domain=%s where cname_domain=%s", (cname_domains[domain],domain,)  )
        conn.execute("update user_package set cname_domain=%s where cname_domain=%s", (cname_domains[domain], domain,) )
        conn.execute("update site set cname_domain=%s where cname_domain=%s", (cname_domains[domain], domain,) )
        conn.execute("update stream set cname_domain=%s where cname_domain=%s", (cname_domains[domain], domain,) )
    
    conn.commit()

    # 修改表结构
    conn.execute("alter table package modify cname_domain int(11);")
    conn.execute("alter table user_package modify cname_domain int(11);")
    conn.execute("alter table site modify cname_domain int(11);")
    conn.execute("alter table stream modify cname_domain int(11);")
    conn.commit()

    # 增加外键
    if not conn.fetchone("select * from INFORMATION_SCHEMA.KEY_COLUMN_USAGE where CONSTRAINT_NAME='package_ibfk_4'"):
        conn.execute("alter table package add CONSTRAINT `package_ibfk_4` FOREIGN KEY (`cname_domain`) REFERENCES `cname_domain` (`id`);")

    if not conn.fetchone("select * from INFORMATION_SCHEMA.KEY_COLUMN_USAGE where CONSTRAINT_NAME='user_package_ibfk_4'"):
        conn.execute("alter table user_package add CONSTRAINT `user_package_ibfk_4` FOREIGN KEY (`cname_domain`) REFERENCES `cname_domain` (`id`);")

    if not conn.fetchone("select * from INFORMATION_SCHEMA.KEY_COLUMN_USAGE where CONSTRAINT_NAME='site_ibfk_2'"):
        conn.execute("alter table site add CONSTRAINT `site_ibfk_2` FOREIGN KEY (`cname_domain`) REFERENCES `cname_domain` (`id`);")

    if not conn.fetchone("select * from INFORMATION_SCHEMA.KEY_COLUMN_USAGE where CONSTRAINT_NAME='stream_ibfk_2'"):
        conn.execute("alter table stream add CONSTRAINT `stream_ibfk_2` FOREIGN KEY (`cname_domain`) REFERENCES `cname_domain` (`id`);")
        
    conn.commit()

    # 自定义hostname
    conn.execute("alter table node_group modify cname_hostname varchar(255);")
    conn.execute('''update node_group set cname_hostname = concat(cname_hostname,".n") where INSTR(`cname_hostname`, '.') = 0 ''')

    if conn.fetchone("SELECT column_name FROM information_schema.columns WHERE table_schema='cdn' and table_name = 'site' AND column_name = 'cname_hostname2';"):
        conn.execute('''update site set cname_hostname = concat(cname_hostname,".",cname_hostname2) where cname_hostname2 is not null and cname_hostname2 != "" and INSTR(`cname_hostname`, '.') = 0;''')
        conn.execute("alter table site drop cname_hostname2")

    if conn.fetchone("SELECT column_name FROM information_schema.columns WHERE table_schema='cdn' and table_name = 'stream' AND column_name = 'cname_hostname2';"):
        conn.execute('''update stream set cname_hostname = concat(cname_hostname,".",cname_hostname2) where cname_hostname2 is not null and cname_hostname2 != "" and INSTR(`cname_hostname`, '.') = 0;''')
        conn.execute("alter table stream drop cname_hostname2;")

    if conn.fetchone("SELECT column_name FROM information_schema.columns WHERE table_schema='cdn' and table_name = 'user_package' AND column_name = 'cname_hostname2';"):
        conn.execute('''update user_package set cname_hostname = concat(cname_hostname,".",cname_hostname2) where cname_hostname2 is not null and cname_hostname2 != ""  and INSTR(`cname_hostname`, '.') = 0; ''')
        conn.execute("alter table user_package drop cname_hostname2;")


    conn.commit()
    

except:
    conn.rollback()
    raise

finally:
    conn.close()
EOF

/opt/venv/bin/python /tmp/_db.py


# 更新panel或conf
flist='master/panel/console/index.html
master/panel/src/views/node/dns/index.html
master/panel/src/views/node/group/groupform.html
master/panel/src/views/node/group/index.html
master/panel/src/views/node/group/line.html
master/panel/src/views/package/basic/addform.html
master/panel/src/views/package/basic/index.html
master/panel/src/views/package/basic/sync.html
master/panel/src/views/package/my/index.html
master/panel/src/views/package/sold/editform.html
master/panel/src/views/package/sold/index.html
master/panel/src/views/package/sold/sync.html
master/panel/src/views/site/site/edit.html
master/panel/src/views/site/site/index.html
master/panel/src/views/stream/stream/edit.html
master/panel/src/views/stream/stream/index.html
master/panel/src/views/system/config/index.html
master/panel/src/views/node/dns/domain.html
master/panel/src/views/site/site/update-cname-domain.html
master/panel/src/views/stream/stream/update-cname-domain.html'

for f in `echo $flist`;do
\cp -a /opt/$dir_name/$f /opt/cdnfly/$f
done

}

update_file() {
cd /opt/$dir_name/master/
for i in `find ./ | grep -vE "^./$|^./agent$|^./conf$|conf/config.py|conf/nginx_global.tpl|conf/supervisor_master.conf|conf/nginx_http_default.tpl|conf/nginx_http_vhost.tpl|conf/nginx_stream_vhost.tpl|conf/ssl.cert|conf/ssl.key|^./panel"`;do
    \cp -aT $i /opt/cdnfly/master/$i
done

}

# 定义版本
version_name="v5.2.0"
version_num="50200"
dir_name="cdnfly-master-$version_name"
tar_gz_name="$dir_name-$(get_sys_ver).tar.gz"

# 下载安装包
cd /opt
echo "开始下载$tar_gz_name..."
download "https://dl2.cdnfly.cn/cdnfly/$tar_gz_name" "https://us.centos.bz/cdnfly/$tar_gz_name" "$tar_gz_name"
echo "下载完成"

echo "开始解压..."
rm -rf $dir_name
tar xf $tar_gz_name
echo "解压完成"

cd /opt
echo "准备升级数据库..."
upgrade_db
echo "升级数据库完成"

echo "更新文件..."
update_file
echo "更新文件完成."

echo "修改config.py版本..."
sed -i "s/VERSION_NAME=.*/VERSION_NAME=\"$version_name\"/" /opt/cdnfly/master/conf/config.py
sed -i "s/VERSION_NUM=.*/VERSION_NUM=\"$version_num\"/" /opt/cdnfly/master/conf/config.py
echo "修改完成"

echo "开始重启主控..."
supervisorctl restart all
#supervisorctl reload
echo "重启完成"

# 修复记录
source /opt/venv/bin/activate
cd /opt/cdnfly/master/tasks
python -c "import record_repair;print record_repair.run_now()"  || true
deactivate    

echo "清理文件"
rm -rf /opt/$dir_name
rm -f /opt/$tar_gz_name
echo "清理完成"

echo "完成$version_name版本升级"